//
//  FZRegisterViewController.m
//  EnglishTalk
//
//  Created by CyonLeuPro on 15/9/7.
//  Copyright (c) 2015年 Feizhu Tech. All rights reserved.
//

#import "FZRegisterViewController.h"
#import "UIButton+FZGreenButton.h"
#import "FZAgreementDeclareViewController.h"
//#import "FZHTTPRequestOperationManager.h"
#import "FCUtil.h"
#import "SRAPICreater.h"
#import "SRLoginUser.h"
#import "OpenUDID.h"
#import "FZSpeechVerificationView.h"
#import "SRCommonWebViewController.h"

@interface FZRegisterViewController ()<UITextFieldDelegate, UIAlertViewDelegate,FZSpeechVerificationViewDelegate>

@property (weak, nonatomic) IBOutlet UIView *inputBackgroundView;
@property (weak, nonatomic) IBOutlet UITextField *usernameTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UIView *firstLineView;
@property (weak, nonatomic) IBOutlet UIView *secondLineView;

@property (weak, nonatomic) IBOutlet UITextField *checkNumberTextField;
@property (weak, nonatomic) IBOutlet UIButton *registerButton;
@property (weak, nonatomic) IBOutlet UIButton *agreementButton;
@property (weak, nonatomic) IBOutlet UIButton *getCheckNumberButton;
@property (weak, nonatomic) IBOutlet UILabel *getCheckNumberLabel;
@property (weak, nonatomic) IBOutlet UIView *bottomLineView;

/**
 *  语音验证视图
 */
@property (strong, nonatomic)FZSpeechVerificationView *sVerView;

@property (strong, nonatomic) NSTimer *timer;//验证码倒计时 60秒
@property (assign, nonatomic) NSUInteger timeCount;//倒计时
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *firstLineHeightConstraint;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *secondLineHeightConstraint;

@end

@implementation FZRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self setupData];
    [self setupView];
    
//    [self.usernameTextField becomeFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setupData {
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateGetCheckNumberButtonTitle) userInfo:nil repeats:YES];
    [self.timer setFireDate:[NSDate distantFuture]];
}

- (void)setupView {
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    
    if (self.isResetPassword) {
        self.title = @"重置密码";
        [self.registerButton setTitle:@"重置" forState:UIControlStateNormal];
        self.agreementButton.hidden = YES;
    } else {
        self.title = @"注册帐号";
        [self.registerButton setTitle:@"注册" forState:UIControlStateNormal];
        
        // 添加注册同意按钮
        NSString *preString = @"点击注册即同意";
        NSString *tipString = @"《安装使用协议》";
        
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@", preString, tipString] attributes:@{NSFontAttributeName:css.fontOfH6, NSForegroundColorAttributeName:css.color_5}];
        [attributedString addAttribute:NSForegroundColorAttributeName value:css.color_1 range:NSMakeRange(preString.length, tipString.length)];
        
        [self.agreementButton setAttributedTitle:attributedString forState:UIControlStateNormal];
    }
    
    self.view.backgroundColor  = css.color_2;
    
//    self.inputBackgroundView.layer.borderColor = css.colorOfSeperatorOnLightBackground.CGColor;
//    self.inputBackgroundView.layer.borderWidth = 0.5;
    
    self.firstLineView.backgroundColor = css.colorOfSeperatorOnLightBackground;
    self.secondLineView.backgroundColor = css.colorOfSeperatorOnLightBackground;
    self.bottomLineView.backgroundColor = css.colorOfSeperatorOnLightBackground;
    
    self.usernameTextField.placeholder = @"手机号";
    self.passwordTextField.placeholder = @"6-18位字母数字组合密码";
    self.checkNumberTextField.placeholder = @"输入验证码";
    
    [self.registerButton applyEllipseGreenBackgroundColor];
    [self.registerButton setEnabled:NO];
    
    self.getCheckNumberLabel.font = css.fontOfH6;
    self.getCheckNumberLabel.textColor = css.color_6;
    self.getCheckNumberLabel.text = @"获取验证码";
    [self.getCheckNumberButton setEnabled:NO];
    
    self.usernameTextField.font = self.passwordTextField.font = self.checkNumberTextField.font = css.fontOfH6;
    self.usernameTextField.textColor = self.passwordTextField.textColor = self.checkNumberTextField.textColor = css.color_6;
    self.usernameTextField.delegate = self.passwordTextField.delegate = self.checkNumberTextField.delegate = self;
    
    //self.firstLineHeightConstraint.constant = 0.5f;
    //self.secondLineHeightConstraint.constant = 0.5f;
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapGesture:)];
    [self.view addGestureRecognizer:tapGesture];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextDidChangeNotification:) name:UITextFieldTextDidChangeNotification object:self.usernameTextField];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextDidChangeNotification:) name:UITextFieldTextDidChangeNotification object:self.passwordTextField];
    
//    self.sVerView = [[FZSpeechVerificationView alloc] init];
//    self.sVerView.delegate = self;
//    [self.view addSubview:self.sVerView];
//    WEAKSELF
//    [self.sVerView mas_makeConstraints:^(MASConstraintMaker *make){
//        make.top.equalTo(weakSelf.passwordTextField.mas_bottom).offset(10);
//        make.trailing.equalTo(weakSelf.view).offset(0);
//        make.width.mas_equalTo(220);
//        make.height.mas_equalTo(35);
//    }];

}

-(void)dealloc{
//    [self.sVerView clear];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


#pragma mark - Button Event 

- (IBAction)onRegisterButton:(UIButton *)sender {
    [self.view endEditing:YES];
    if ([self checkViladInput]) {
        if (self.isResetPassword) {
            [self sendResetPassword];
        } else {
            [self sendRegisterUser];
        }
    }
}


- (IBAction)onGetCheckNumberButton:(UIButton *)sender {
    [sender setEnabled:NO];
    [self.view endEditing:YES];
    NSString *mobile = [self stringTrimWhiteSpaceWithSourceString:self.usernameTextField.text];
    
    if (!mobile || [mobile length] < 11) {
        [self showHUDHintWithText:@"手机号错误！"];
        return;
    }
    
    if (![FCUtil isValidateMobilePhoneNumber:mobile]) {
        [self showHUDHintWithText:@"请填写正确的手机号码"];
        return;
    }
    [self queryCheckNumber];
}

- (IBAction)onAgreementButton:(UIButton *)sender {
//    FZAgreementDeclareViewController *viewController = [[FZAgreementDeclareViewController alloc] initWithNibName:@"FZAgreementDeclareViewController" bundle:nil];
//    
//    [self.navigationController pushViewController:viewController animated:YES];
    
    FZBasicURLModel *urlModel = [SRLoginManager sharedManager].basicURLModel;
    if (urlModel && [urlModel.use_protocol length] > 0) {
        [self showWebVCWith:urlModel.use_protocol title:@"使用协议"];
    } else {
        WEAKSELF
        [self startProgressHUD];
        [[SRLoginManager sharedManager] queryBasicUrlWithSuccess:^(NSInteger statusCode, NSString *message, id responseDataObject) {
            [weakSelf stopProgressHUD];
            if (statusCode == kFZRequestStatusCodeSuccess) {
                FZBasicURLModel *model = responseDataObject;
                [weakSelf showWebVCWith:model.use_protocol title:@"使用协议"];
            } else {
                [weakSelf showHUDErrorMessage:message];
            }
        } failure:^(id responseObject, NSError *error) {
            [weakSelf stopProgressHUD];
            [weakSelf showHUDError];
        }];
        
    }
    
}
- (void)showWebVCWith:(NSString *)urlString title:(NSString *)title {
    SRCommonWebViewController *vc = [[SRCommonWebViewController alloc] init];
    vc.urlString = urlString;
    vc.titleStr = title;
    [self.navigationController pushViewController:vc animated:YES];
}


- (void)onTapGesture:(UITapGestureRecognizer *)gesture {
    [self.view endEditing:YES];
}

/**
 *  向服务端发送注册请求
 */
- (void)sendRegisterUser {
    NSString *mobile = [self stringTrimWhiteSpaceWithSourceString:self.usernameTextField.text];
    NSString *password = [self stringTrimWhiteSpaceWithSourceString:self.passwordTextField.text];
    NSString *checkNumStr = [self stringTrimWhiteSpaceWithSourceString:self.checkNumberTextField.text];
    NSString *devicetoken = [self uniqID];
    
    NSDictionary *parameters = [@{} mutableCopy];
    [parameters setValue:mobile forKey:@"mobile"];
//    [parameters setValue:[FCUtil md5HexString:password] forKey:@"password"];
    [parameters setValue:password forKey:@"password"];

    [parameters setValue:checkNumStr forKey:@"code"];
    [parameters setValue:devicetoken forKey:@"devicetoken"];
    NSString *jsonStr = [FCUtil getDeviceInfoJsonString];
    [parameters setValue:jsonStr forKey:@"device_info"];
    WEAKSELF
    [self startProgressHUDWithText:@"正在注册..."];
    NSString *urlString = [[SRAPICreater sharedInstance] APIWithName:@"user_register"];
    
    
    [[SRNetWorkManager sharedInstance] POSTNODefaultParamWithUrl:urlString parameters:parameters responseClass:nil success:^(NSInteger statusCode, NSString *message, id dataObject){
        [weakSelf stopProgressHUD];
        if (statusCode == kFZRequestStatusCodeSuccess) {
            [SRLoginUser setPhone:mobile];
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"注册成功" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
            [alertView show];
            
        } else {
            if (message) {
                [weakSelf showHUDHintWithText:message];
            } else {
                [weakSelf showHUDHintWithText:@"注册失败，请重试！"];
            }
        }
        
    } failure:^(id responseObject, NSError *error) {
        [weakSelf stopProgressHUD];
        [weakSelf showHUDHintWithText:@"注册失败，请重试！"];
    }];
}

- (void)sendResetPassword {
    NSString *mobile = [self stringTrimWhiteSpaceWithSourceString:self.usernameTextField.text];
    NSString *password = [self stringTrimWhiteSpaceWithSourceString:self.passwordTextField.text];
    NSString *checkNumStr = [self stringTrimWhiteSpaceWithSourceString:self.checkNumberTextField.text];
//    NSString *devicetoken = [self uniqID];
    
    NSDictionary *parameters = [@{} mutableCopy];
    [parameters setValue:mobile forKey:@"mobile"];
//    [parameters setValue:[FCUtil md5HexString:password] forKey:@"password"];
    [parameters setValue:password forKey:@"password"];

//    [parameters setValue:[FCUtil md5HexString:password] forKey:@"newpassword"];

    [parameters setValue:checkNumStr forKey:@"code"];
//    [parameters setValue:devicetoken forKey:@"devicetoken"];
    
    WEAKSELF
    [self startProgressHUD];
    NSString *urlString = [[SRAPICreater sharedInstance] APIWithName:@"user_resetPassword"];
    [[SRNetWorkManager sharedInstance] POSTNODefaultParamWithUrl:urlString parameters:parameters responseClass:nil success:^(NSInteger statusCode, NSString *message, id dataObject) {
        [weakSelf stopProgressHUD];
        if (statusCode == kFZRequestStatusCodeSuccess) {
            [weakSelf showHUDHintWithText:@"重置成功"];
            [weakSelf.navigationController popViewControllerAnimated:YES];

        } else {
            if (message) {
                [weakSelf showHUDHintWithText:message];
            } else {
                [weakSelf showHUDHintWithText:@"重置失败"];
            }
        }
        
    } failure:^(id responseObject, NSError *error) {
        [weakSelf stopProgressHUD];
        [weakSelf showHUDHintWithText:@"重置失败"];
    }];
}

- (void)bindPhone {
    NSString *mobile = [self stringTrimWhiteSpaceWithSourceString:self.usernameTextField.text];
    NSString *password = [self stringTrimWhiteSpaceWithSourceString:self.passwordTextField.text];
    NSString *checkNumStr = [self stringTrimWhiteSpaceWithSourceString:self.checkNumberTextField.text];
        //    NSString *devicetoken = [self uniqID];
    
    NSDictionary *parameters = [@{} mutableCopy];
    [parameters setValue:mobile forKey:@"mobile"];
//    [parameters setValue:[FCUtil md5HexString:password] forKey:@"password"];
    [parameters setValue:password forKey:@"password"];

    [parameters setValue:checkNumStr forKey:@"code"];
    
    WEAKSELF
    [self startProgressHUD];
    NSString *urlString = [[SRAPICreater sharedInstance] APIWithName:@"user_resetPassword"];
    [[SRNetWorkManager sharedInstance] POST:urlString needCache:NO parameters:parameters responseClass:nil success:^(NSInteger statusCode, NSString *message, id dataObject) {
        [weakSelf stopProgressHUD];
        if (statusCode == kFZRequestStatusCodeSuccess) {
            [weakSelf showHUDHintWithText:@"绑定成功"];
            [weakSelf.navigationController popViewControllerAnimated:YES];
            
        } else {
            if (message) {
                [weakSelf showHUDHintWithText:message];
            } else {
                [weakSelf showHUDHintWithText:@"绑定失败"];
            }
        }
        
    } failure:^(id responseObject, NSError *error) {
        [weakSelf stopProgressHUD];
        [weakSelf showHUDHintWithText:@"绑定失败"];
    }];
}


- (void)updateGetCheckNumberButtonTitle {

    NSString *title = [NSString stringWithFormat:@"(%lu)%@", (unsigned long)self.timeCount, @"重新获取"];
    self.getCheckNumberLabel.text = title;
    
    if (self.timeCount <= 0) {
        //计时完成，重新获取
        [self resetCheckNumberButton];
        [self.sVerView setAvailable:YES];
    }
    -- self.timeCount;
}

- (void)resetCheckNumberButton {
    [self.timer setFireDate:[NSDate distantFuture]];
    [self.getCheckNumberButton setEnabled:YES];
    self.getCheckNumberLabel.textColor = [FZStyleSheet currentStyleSheet].colorOfGreenButtonNormal;
    self.getCheckNumberLabel.text = @"获取验证码";
}

- (void)queryCheckNumber {
    NSString *mobile = [self stringTrimWhiteSpaceWithSourceString:self.usernameTextField.text];
    
    NSString *urlString = [[SRAPICreater sharedInstance] APIWithName:@"user_mobileCode"];
    NSMutableDictionary *params = [@{} mutableCopy];
    
    [params setValue:mobile forKey:@"mobile"];
    //[params setValue:@(0) forKey:@"type"];
    
    if (self.isResetPassword) {
        [params setValue:@(1) forKey:@"isreset"];
    } else {
        [params setValue:@(0) forKey:@"isreset"];
    }
    if (self.isResetPassword) {
        [params setValue:@(3) forKey:@"type"];
    } else {
        [params setValue:@(1) forKey:@"type"];
    }
    [self startProgressHUD];
    WEAKSELF
    [[SRNetWorkManager sharedInstance] POSTNODefaultParamWithUrl:urlString parameters:params responseClass:nil success:^(NSInteger statusCode, NSString *message, id dataObject) {
        [weakSelf stopProgressHUD];
        if (statusCode == kFZRequestStatusCodeSuccess) {
            [weakSelf showHUDHintWithText:@"短信已经发送，请注意查收"];
            
            FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
            weakSelf.timeCount = 60;
            [weakSelf.timer setFireDate:[NSDate distantPast]];
            weakSelf.getCheckNumberLabel.textColor = css.colorOfGreenButtonDisabled;
            [weakSelf.timer fire];
            [weakSelf.sVerView setAvailable:NO];

        } else {
            [weakSelf resetCheckNumberButton];
            NSString *errorMessage = message;
            if (!message) {
                errorMessage = @"发送失败";
            }
            [weakSelf showHUDHintWithText:errorMessage];
        }
    } failure:^(id responseObject, NSError *error) {
        [weakSelf stopProgressHUD];
        [weakSelf resetCheckNumberButton];
        [weakSelf showHUDHintWithText:@"发送失败"];
    }];
}



#pragma mark - UITextFieldDelegate 


- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (self.usernameTextField == textField) {
        [self.passwordTextField becomeFirstResponder];
    } else if (self.passwordTextField == textField) {
        [self.checkNumberTextField becomeFirstResponder];
    } else {
        //注册
        [self.view endEditing:YES];
        if ([self checkViladInput]) {
            if (self.isResetPassword) {
                [self sendResetPassword];
            } else if (self.isBindPhone) {
                [self bindPhone];
            }
            else {
                [self sendRegisterUser];
            }
        }
    }
    
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if(textField == self.passwordTextField){
        NSString *passwordText = textField.text;
        if(passwordText.length >= 18){
            return NO;
        }
    }
    return YES;
}

#pragma mark -- uialert delegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Private Method 

-(NSString*)uniqID {
    NSString* uniqueIdentifier = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    return uniqueIdentifier;
}

- (NSString *)stringTrimWhiteSpaceWithSourceString:(NSString *)sourceString {
    NSCharacterSet *whitespace = [NSCharacterSet  whitespaceAndNewlineCharacterSet];
    NSString *resultString = [sourceString stringByTrimmingCharactersInSet:whitespace];
    if (resultString && resultString.length > 0) {
        return resultString;
    }
    
    return nil;
}


- (BOOL)checkViladInput {
    [self.view endEditing:YES];

    NSString *mobile = [self stringTrimWhiteSpaceWithSourceString:self.usernameTextField.text];
    if (!mobile || [mobile length] < 11) {
        [self showHUDHintWithText:@"手机号错误！"];
        return NO;
    }
    
    if (![FCUtil isValidateMobilePhoneNumber:mobile]) {
        [self showHUDHintWithText:@"请填写正确的手机号码"];
        return NO;
    }
    
    NSString *password = [self stringTrimWhiteSpaceWithSourceString:self.passwordTextField.text];
    if (!password || [password length] < 6) {
        [self showHUDHintWithText:@"密码最少6位"];
        return NO;
    }
    
    if (![FCUtil isValidatePassword:password]) {
        [self showHUDHintWithText:@"密码太简单"];
        return NO;
    }
    
    NSString *checkNumStr = [self stringTrimWhiteSpaceWithSourceString:self.checkNumberTextField.text];
    if (!checkNumStr) {
        [self showHUDHintWithText:@"请输入验证码"];
        return NO;
    }
    
    return YES;
}

- (void)textFieldTextDidChangeNotification:(NSNotification *)notification {
    if (notification.object == self.usernameTextField) {
        FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
        NSString *phone = [self stringTrimWhiteSpaceWithSourceString:self.usernameTextField.text];
        if (phone) {
            [self.getCheckNumberButton setEnabled:YES];
            [self.sVerView setAvailable:YES];
            self.getCheckNumberLabel.textColor = css.colorOfGreenButtonNormal;
        } else {
            [self.getCheckNumberButton setEnabled:NO];
            [self.sVerView setAvailable:NO];
            self.getCheckNumberLabel.textColor = css.colorOfGreenButtonDisabled;
        }
    } else if (notification.object == self.passwordTextField) {
//        NSLog(@"password");
    }
    
    if ([self stringTrimWhiteSpaceWithSourceString:self.usernameTextField.text] && [self stringTrimWhiteSpaceWithSourceString:self.passwordTextField.text]) {
        [self.registerButton setEnabled:YES];
    } else {
        [self.registerButton setEnabled:NO];
    }
}

#pragma mark FZSpeechVerificationViewDelegate
/**
 *  剩余超时的时间
 *
 */
- (void)sVerRemainTime:(NSInteger)time{
    if(time <= 0){
        //超时
        [self resetCheckNumberButton];
    }
}

/**
 *  请求进度显示
 */
-(void)sVerStartProgress{
    [self startProgressHUD];
}

/**
 *  请求进度消失
 *
 */
-(void)sVerStopProgress:(NSString*)msg{
    [self stopProgressHUD];
    if(msg){
       [self showHUDErrorMessage:msg];
    }else{
        [self.getCheckNumberButton setEnabled:NO];
        self.getCheckNumberLabel.textColor = [FZStyleSheet currentStyleSheet].colorOfGreenButtonDisabled;
    }
}

/**
 *  获取验证需要的参数
 *
 */
-(NSMutableDictionary*)sVerParamas{
    NSString *mobile = [self stringTrimWhiteSpaceWithSourceString:self.usernameTextField.text];
    NSMutableDictionary *params = [@{} mutableCopy];
    [params setValue:mobile forKey:@"mobile"];
    if (self.isResetPassword) {
        [params setValue:@(1) forKey:@"isreset"];
    } else {
        [params setValue:@(0) forKey:@"isreset"];
    }
    if (self.isResetPassword) {
        [params setValue:@(3) forKey:@"type"];
    } else {
        [params setValue:@(1) forKey:@"type"];
    }
    return params;
}

@end
